from itsdangerous import TimedJSONWebSignatureSerializer
from comment.utils import const
from flask import current_app
from comment.models.user import User


def generate_token(uid):
    """
    创建加密的token
    :param uid: 用户ID
    :param expiration: 有效时间(秒)
    :return:
    """
    s = TimedJSONWebSignatureSerializer(secret_key=const.SECRET_KEY, expires_in=const.JWT_EXPIRY_SECOND)
    # 生成token
    return s.dumps({'id': uid}).decode()


def verify_token(token_str):
    """
    验证token,成功之后返回用户的id
    :param token_str:
    :return:
    """
    s = TimedJSONWebSignatureSerializer(secret_key=const.SECRET_KEY)
    try:
        data = s.loads(token_str)
    except Exception as e:
        current_app.logger.error(e)
        return {'msg': 'token 验证失败'}, 400
    user = User.query.filter(User.id == data['id']).first()
    if user and user.status != 0:
        return {'msg': '用户已经过期'}, 400
    return {'id': user.id}

